<template>
<div class="containerWrap">
  <el-container class="container">
    <el-aside class="appTree" width="200px">
      <app-tree v-bind:tree-data="treeData"
                v-on:appTreeClick="treeClickHandle"></app-tree>
    </el-aside>
    <el-main class="rightMain">
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>
              单位名称：<el-input size="small" placeholder="请输入名称" v-model="queryData.name" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              联系人：<el-input size="small" placeholder="请输入联系人" v-model="queryData.firstResponsibilityId" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              联系电话：<el-input size="small" placeholder="请输入联系电话" v-model="queryData.firstResponsibilityPhone" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              <el-button size="small" @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button>
            </div>
          </div>
        </el-header>
        <el-main class="tableMain">
          <app-table :page-data="pageData"
                     :table-columns="tableColumns"
                     v-on:currentChange="handleCurrentChange"
                     v-on:handleCheckedRows="handleCheckedRows"/>
        </el-main>
        <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible"  :close-on-click-modal="false" :before-close="close" class="dialog_style">
          <div class="formWrapper">
            <el-form class="formMain" :model="formData"
                    :rules="rules"
                    ref="formData"
                    label-width="90px"
                    size="small">
              <el-divider content-position="left">基本信息</el-divider>
              <el-row :gutter="15">
                <el-col :span="12">
                  <el-form-item label="单位名称：" prop="name">
                    <el-input v-model="formData.name" placeholder="名称"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="上级：" >
                    <div class="block">
                      <el-cascader placeholder="请选择" style="width:100%"
                      :options="treeOption" filterable clearable
                      :props="gridIdProps"
                      :show-all-levels="false"
                      v-model="formData.allIdArr">
                      </el-cascader>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="单位电话：" prop="phone">
                    <el-input v-model="formData.phone" placeholder="电话"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="负责人：" prop="firstResponsibilityId">
                     <el-input v-model="formData.firstResponsibilityId" placeholder="负责人"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="负责人手机：" label-width="95px" prop="firstResponsibilityPhone">
                    <el-input v-model="formData.firstResponsibilityPhone" placeholder="负责人手机"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="地址：" prop="address">
                    <el-input v-model="formData.address" placeholder="地址"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="选择经纬度：" label-width="90px" prop="longitude">
                    <el-row>
                      <el-col :span="10">
                      <el-input v-model="formData.longitude" :disabled="true" placeholder="经度" ></el-input>
                      </el-col>
                      <el-col :span="1" style="text-align: center">-</el-col>
                      <el-col :span="10">
                        <el-input v-model="formData.latitude" :disabled="true" placeholder="纬度" ></el-input>
                      </el-col>
                      <el-col :span="3">
                        <el-button type="text" @click="openSimpleMap">&nbsp;&nbsp;从地图选择</el-button>
                      </el-col>
                    </el-row>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item class="spcialLabel5" label="简介：" prop="remark">
                    <el-input v-model="formData.remark" type="textarea" :rows="5" placeholder="请输入简介"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="照片" class="spcialLabel5">
                    <app-upload ref="appUpload"
                                v-model="formData.picture"></app-upload>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div v-if="!showOnly" slot="footer" class="dialog-footer">
              <el-button size="small" @click="cancel('formData')">取 消</el-button>
              <el-button size="small" type="primary" :disabled="showOnly" @click="save('formData')">提 交</el-button>
            </div>
          </div>
        </el-dialog>
        <el-dialog class="dialog-body-mini dialog-body-map" :visible.sync="showMap" title="地图标记" width="70%" top="8vh" :before-close="mapCancel">
          <edit-map v-if="showMap" :mode="mapMode" @appMapCallback="appMapCallback" :target="mapTarget" :row-id="currentSelectedRowId"></edit-map>
        </el-dialog>
        <!-- 系统用户 start -->
        <el-dialog title="系统用户" :visible.sync="dialogUserVisible" :before-close="closeUser" class="dialog_style">
          <el-table :data="usersData"
            :header-cell-style="{backgroundColor:'rgb(207, 31, 0)', color: '#fff'}"
            highlight-current-row
            @current-change="handleRowClick">
            <el-table-column v-for="(item, index) in UsersColumns"
              :key="index"
              :prop="item.prop"
              :label="item.label"
              :formatter="item.formatter"
              :show-overflow-tooltip="true">
            </el-table-column>
          </el-table>
          <div style="width:100%;height:20px"></div>
          <el-pagination background
            @current-change="handleCurrentUserChange"
            :current-page.sync="currentPage"
            :page-size="!usersPage.limit ? 10 : usersPage.limit"
            layout="total, prev, pager, next, jumper"
            :total="usersPage.total">
          </el-pagination>
          <div slot="footer" class="dialog-footer">
            <el-button size="small" @click="closeUser">取 消</el-button>
            <el-button size="small" @click="sureUser" type="primary">确 定</el-button>
          </div>
        </el-dialog>
        <!-- 系统用户 end -->
      </el-container>
    </el-main>
  </el-container>
</div>
</template>

<script>
import AppUpload from '@/components/AppUpload'
import AppTree from '@/components/common/AppTree'
import BtnGroup from '@/components/BtnGroup'
import AppTable from '@/components/AppTable'
import EditMap from '@/components/EditMap'
import { createUnit, findUnit, updateUnit, deleteUnit, getUnit, findUser } from '@/http/setApi'
import { findUnitTree, findDeptList } from '@/http/AppApi'
import { getAllRegion, getAllRegionObj } from '@/utils/region'
import {validatePhone, validateMobile} from '@/utils/validate'
export default {
  data () {
    return {
      active: 1,
      currentPage: 1,
      mapMode: 'full',
      dialogTitle: '新增单位',
      currentSelectedRowId: '',
      showMap: false,
      showOnly: false,
      dialogFormVisible: false,
      dialogUserVisible: false,
      usersData: [],
      treeData: [],
      deptOption: [],
      treeOption: [],
      currentSelectedData: [],
      formData: {},
      pageData: {},
      usersPage: {},
      queryData: {},
      mapTarget: {},
      currentUserData: {},
      queryUsersData: {},
      gridIdProps: {
        label: 'name',
        value: 'id',
        checkStrictly: true
      },
      tableColumns: [
        { label: '单位名称', prop: 'name' },
        { label: '上级单位', prop: 'parentId', formatter: this.unitFormatter },
        { label: '联系人', prop: 'firstResponsibilityId' },
        { label: '联系电话', prop: 'firstResponsibilityPhone' },
        { label: '单位电话', prop: 'phone' },
        { label: '地址', prop: 'address' }
      ],
      UsersColumns: [
        { label: '账号', prop: 'account' },
        { label: '姓名', prop: 'name' },
        { label: '联系方式', prop: 'phone' },
        { label: '身份证号码', prop: 'idCardNumber' },
        { label: '部门名称', prop: 'deptId', formatter: this.deptFormatter },
        { label: '启用状态', prop: 'disableStatus', formatter: this.statustFormatter }
      ],
      dataPickerBeforeTodayOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      },
      rules: {
        name: [{
          required: true,
          message: '填写账号',
          trigger: 'blur'
        }],
        allIdArr: [{
          required: true,
          message: '选择上级',
          trigger: 'change'
        }],
        unitPhone: [{
          required: true,
          validator: validateMobile,
          message: '填写单位电话',
          trigger: 'blur'
        }],
        firstResponsibilityId: [{
          required: true,
          message: '负责人',
          trigger: 'change'
        }],
        firstResponsibilityPhone: [{
          required: true,
          validator: validatePhone,
          message: '请填负责人手机',
          trigger: 'blur'
        }]
      }
    }
  },
  mounted () {
    this.getTableData()
    this.getUnitTree()
  },
  components: {AppTree, BtnGroup, AppTable, EditMap, AppUpload},
  methods: {
    deptFormatter (row, column) {
      let options = this.deptOption
      let deptName = ''
      for (let i = 0; i < options.length; i++) {
        const element = options[i]
        if (element.id === row.deptId) {
          deptName = element.name
        }
      }
      return deptName
    },
    unitFormatter (row, column) {
      let regionData = {}
      regionData.id = row.parentId
      regionData.items = this.treeData
      let gridIdArr = getAllRegionObj(regionData)
      if (gridIdArr && gridIdArr.length > 0) {
        return gridIdArr[gridIdArr.length - 1].name
      } else {
        return ''
      }
    },
    statustFormatter (row) {
      return row.disableStatus === 1 ? '启用' : '未启用'
    },
    save (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.beforeSubmit()
          if (this.formData.id) {
            updateUnit(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.getTableData()
                this.getUnitTree()
                this.cancel(formName)
                this.$message({
                  type: 'success',
                  message: '修改成功'
                })
              } else {
                this.$message({
                  type: 'success',
                  message: resp.data
                })
              }
            })
          } else {
            createUnit(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.getTableData()
                this.getUnitTree()
                this.cancel(formName)
                this.dialogFormVisible = false
                this.$refs[formName].resetFields()
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
              } else {
                this.$message({
                  type: 'success',
                  message: resp.data
                })
              }
            })
          }
        }
      })
    },
    beforeSubmit () {
      console.log(this.formData.allIdArr)
      if (this.formData.allIdArr && this.formData.allIdArr.length > 0) {
        let parentId = this.formData.allIdArr[this.formData.allIdArr.length - 1]
        this.$set(this.formData, 'parentId', parentId)
      } else {
        this.$set(this.formData, 'parentId', 0)
      }
      return true
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            deleteUnit(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.$message({type: 'success', message: '删除成功'})
                this.getTableData()
                this.getUnitTree()
              }
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    getTableData () {
      let param = this.queryData
      findUnit(param).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data) {
            this.pageData = data
            if (this.pageData.items && this.pageData.items instanceof Array) {
              this.tableData = this.pageData.items
            }
          }
        } else {
          this.$message({
            type: 'info',
            message: resp.message
          })
          return ''
        }
      })
    },
    getUserTable () {
      let param = this.queryUsersData
      findUser(param).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data) {
            this.usersPage = data
            this.usersData = data.items
          }
        } else {
          this.$message({
            type: 'info',
            message: resp.message
          })
          return ''
        }
      })
    },
    getUnitTree () {
      findUnitTree().then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          this.treeData = this.treeOption = data
        }
      })
    },
    findDeptList (id) {
      let param = {'unitId': id}
      findDeptList(param).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          this.deptOption = data
        }
      })
    },
    treeClickHandle (data) {
      console.log(data)
      this.queryData = {}
      this.queryData.allId = data.allId
      let regionData = {}
      regionData.id = data.id
      regionData.items = this.treeData
      let gridIdArr = getAllRegion(regionData)
      this.$set(this.formData, 'allIdArr', gridIdArr)
      this.getTableData()
    },
    btnClickCallback (callbackData) {
      this.dialogFormVisible = true
      this.showOnly = callbackData.showOnly
      this.dialogTitle = callbackData.dialogTitle
      console.log(callbackData)
      if (callbackData.btnType === 'post') {
        this.formData = this.formData.allIdArr ? this.formData : {}
      } else if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else {
        let data = callbackData.rows[0]
        this.getUnit(data.id)
      }
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.currentSelectedData = rows
        this.formData = rows[0]
        this.currentSelectedRowId = rows[0].id
      } else {
        this.currentSelectedData = []
      }
    },
    getUnit (id) {
      getUnit(id).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          this.formData = data
          let regionData = {}
          regionData.id = this.formData.parentId
          regionData.items = this.treeData
          let gridIdArr = getAllRegion(regionData)
          this.$set(this.formData, 'allIdArr', gridIdArr)
        }
      })
    },
    handleCurrentChange (val) {
      this.queryData.offset = (val - 1) * 10
      this.getTableData()
    },
    handleCurrentUserChange (val) {
      this.queryUsersData.offset = (val - 1) * 10
      this.getUserTable()
    },
    searchHandleClick () {
      this.queryData.offset = 0
      this.getTableData()
    },
    close (type) {
      this.dialogFormVisible = false
      this.formData = {}
      this.$refs['formData'].resetFields()
    },
    cancel () {
      this.dialogFormVisible = false
      this.formData = {}
      this.$refs['formData'].resetFields()
    },
    handleSelectUser () {
      this.dialogUserVisible = true
      this.getUserTable()
    },
    handleRowClick (rows) { // 单行点击事件
      console.log(rows)
      this.currentUserData = rows
    },
    sureUser () {
      if (this.currentUserData) {
        this.formData = JSON.parse(JSON.stringify(this.currentUserData))
        this.$set(this.formData, 'id', '')
        this.$set(this.formData, 'firstResponsibilityId', this.currentUserData.id)
        this.dialogUserVisible = false
      } else {
        this.$message({
          type: 'info',
          message: '请选择用户'
        })
      }
    },
    closeUser () {
      this.dialogUserVisible = false
    },
    openSimpleMap () {
      this.mapMode = 'simple'
      this.showMap = true
      this.mapHackReset = true
    },
    appMapCallback (appMapInfo) {
      if (appMapInfo.target) {
        if (appMapInfo.target.targetId) {
          let mapLocation = {}
          if (appMapInfo.poly && appMapInfo.poly instanceof Array && appMapInfo.poly.length > 0) {
            let length = appMapInfo.poly.length
            this.saveMapLocationInfoByArray(0, length, appMapInfo)
          } else {
            mapLocation = this.appMapInfo2MapLocation(appMapInfo)
            this.saveMapLocationInfo(mapLocation)
          }
        } else {
          this.showOnly = false
          this.showMap = false
          this.$set(this.formData, 'latitude', appMapInfo.lnglat.lat)
          this.$set(this.formData, 'longitude', appMapInfo.lnglat.lng)
        }
      }
      return ''
    },
    mapCancel () {
      this.mapHackReset = false
      this.showMap = false
    }
  }
}
</script>
<style scoped>
  .containerWrap {
    padding:10px;
    height: 100%;
    box-sizing: border-box
  }
  .container {
    height: 100%;
  }
</style>
